<template>
  <div class="fullMain">
    <div style="position:fixed; width:100%">
      <x-header
        :left-options="{backText: '',showBack: false}"
        :right-options="{showMore: true}"
        @on-click-more="showMenusOfReportActions = true"
      >
        汇报查看
        <i
          slot="overwrite-left"
          class="fa fa-filter leftIcon"
          @click="isShowFilter=!isShowFilter"
        ></i>
      </x-header>
    </div>

    <!-- 右上角的选择 -->
    <div v-transfer-dom>
      <actionsheet
        :menus="reportActions"
        @on-click-menu="selectReportAction"
        v-model="showMenusOfReportActions"
        show-cancel
      ></actionsheet>
    </div>

    <!--插入验证提示框-->
    <div v-transfer-dom>
      <alert v-model="isShowAlert">{{alertText}}</alert>
    </div>

    <!-- 插入底部导航栏 -->
    <NavigationOfReport :flagOfItem.sync="flagOfItem"></NavigationOfReport>

    <!-- 插入筛选页面 -->
    <filterPage @filter="filter" :isShowFilter.sync="isShowFilter" :initParams.sync="initParams"></filterPage>

    <div class="mainHeader" id="selectTop" style="background-color: #efeff4">
      <!-- 搜索和搜索框 -->
      <search class="search" @showRepoOfThisStudent="showRepoOfThisStudent"></search>
    </div>

    <div id="content">
      <dayView @func="getValueFromDayView" v-if="reportType==='日报'"></dayView>
      <weekView @func="getValueFromDayView" v-if="reportType==='周报'"></weekView>
      <monthView @func="getValueFromDayView" v-if="reportType==='月报'"></monthView>
      <yearView @func="getValueFromDayView" v-if="reportType==='年报'"></yearView>
      <graduateView @func="getValueFromDayView" v-if="reportType==='毕业总结'"></graduateView>
    </div>

    <button
      class="button"
      @click="resetQuery()"
      style="background-color: rgba(144,238,144, .6);border-color: rgba(144,238,144, .6);"
    ></button>
  </div>
</template>

<script>
import { XHeader, Actionsheet, Confirm } from "vux";
import { mapState } from "Vuex";
import { compareTimeString } from "utilMethods/sort.js";
import report from "api/report";
import year from "api/year";
import common from "utilMethods/common";
import NavigationOfReport from "components/Navigation/NavigationOfReport.vue";
import dayView from "views-new/common/report/partsOfUViewAll/dayView.vue";
import weekView from "views-new/common/report/partsOfUViewAll/weekView.vue";
import monthView from "views-new/common/report/partsOfUViewAll/monthView.vue";
import yearView from "views-new/common/report/partsOfUViewAll/yearView.vue";
import graduateView from "views-new/common/report/partsOfUViewAll/graduateView.vue";
import search from "views-new/common/report/partsOfUViewAll/search.vue";
import filterPage from "views-new/common/report/partsOfUViewAll/filter.vue";
import group from "api/group";
export default {
  name: "U_view_all",
  components: {
    Confirm,
    XHeader,
    NavigationOfReport,
    Actionsheet,
    dayView,
    weekView,
    monthView,
    yearView,
    graduateView,
    search,
    filterPage,
  },
  data() {
    return {
      toUpdateData: { isShow: true, reports: "" }, // 讲循环显示列表中需要v-if绑定的两个值复合为一个的对象
      indexOfSingleSelected: 0,
      alertText: "", // 验证提示框的文本
      isShowAlert: false, // 是否显示验证提示,
      startDate: "",
      endDate: "",
      member: "",
      group: "", //选择的群组
      allGroups: [], // 存放所有分组
      flagOfItem: "report",
      showMenusOfReportActions: false,
      reportActions: {
        graduation_summary: "毕业总结",
        statistics: "汇报统计",
        task: "发布任务",
      },
      reportType: "",
      isShowFilter: false,
      // 评论相关
      reportCommented: {},
      isShowConfirmComment: false,
      initParams: {},
    };
  },
  mounted() {
    this.getInitParams();
  },
  computed: {
    ...mapState(["reportContentProf"]),
    ...mapState({
        userInfo: state => state.user.userInfo
      })
  },

  watch: {
    reportType(val){
      console.log('reportType变了');
      console.log(val);
    },
    member(val) {
      this.getSinglePeriodData();
      if (this.reportType === "毕业总结") {
        this.getGraduateReport();
      }
    },
    startDate(val) {
      if (this.member !== "") {
        this.getSinglePeriodData();
      }
    },
    endDate(val) {
      // 如果起始时间在截止时间后，将起始时间改为与截止时间相同
      if (compareTimeString(this.startDate, this.endDate) === 1) {
        this.startDate = this.endDate;
      }
      if (this.member !== "") {
        this.getSinglePeriodData();
      }
    },
    group(val) {
      this.$store.commit("stageCurrentGroupId", this.group);
    },
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    showAlert(alertText) {
      this.isShowAlert = true;
      this.alertText = alertText;
    },
    closeTip() {
      this.isShowAlert = false;
      this.alertText = "";
    },
    selectReportAction(value) {
      if ("statistics" === value) {
        this.$router.push({ name: "SituationStatistics" });
      } else if ("graduation_summary" === value) {
        this.$router.push({ name: "S_graduation_summary" });
      } else if ("task" === value) {
        this.$router.push({ name: "CreateTask" });
      }
    },
    resetQuery() {
      this.member = "";
      this.getData();
    },
    // 获取所有群
    async getInitParams() {
      // 设置默认时间
      this.setToday();
      // 设置默认的群组
      this.allGroups.length = 0;
      const result = await group.getGroupsBeIn();
      if (result.code === 0) {
        this.showAlert("查询失败，请重试。");
      } else if (result.data.length === 0) {
        this.showAlert("您暂时没有创建或加入任何群");
      } else {
        let key, value;
        result.data.forEach((element) => {
          key = element.groupId;
          value = element.detail.groupName;
          this.allGroups.push({ key, value });
        });
        //如果是初始化，设置默认群组
        this.group = this.allGroups[0].key;
        // 请求数据
        this.getData();
      // 把初始值存起来，传给filter
        let temp = {
          allGroups: this.allGroups,
          group: this.allGroups[0].key,
          placeholderOfGroup: this.allGroups[0].value,
          endDate: this.endDate,
        };
        this.initParams = temp;
      }
    },
    async getSinglePeriodData() {
      if (this.startDate == "") {
        this.startDate = this.endDate;
      }
      let userIdForQuery;
      userIdForQuery = this.member;
      const result = await report.getReportsByUserId({
        end: this.endDate,
        userId: userIdForQuery,
        start: this.startDate,
      });
      if (result.code === 0) {
        this.showAlert("查询失败，请重试。");
        setTimeout(this.closeTip, 1000);
      } else if (result.data.length === 0) {
        this.toUpdateData.isShow = false;
        this.toUpdateData.reports = "";
        if (this.member !== "") {
          this.showAlert("该用户汇报为空");
          this.member = "";
        }
      } else {
        this.$store.dispatch("getReportContentProf", result.data);
        this.toUpdateData.reports = this.reportContentProf;
      }
    },
    async getData() {
      if (this.startDate == "") {
        this.startDate = common.setDayCompareWithToday(-7);
      }
      if (this.reportType === "日报") {
        this.getDayReport();
      } else if (this.reportType === "周报") {
        this.getWeekReport();
      } else if (this.reportType.indexOf("月") !== -1) {
        this.getMonthReport();
      } else if (this.reportType === "年报") {
        this.getYearReport();
      } else if (this.reportType === "毕业总结") {
        this.getGraduateReport();
      }
    },
    async getDayReport() {
      const result = await report.getReportsByGroupId({
        end: this.endDate,
        groupId: this.group,
        start: this.startDate,
      });
      this.$store.commit("stageReportListQuery", {
        end: this.endDate,
        groupId: this.group,
        start: this.startDate,
      });
      if (result.code === 0) {
        // this.showAlert('查询失败，请重试。')
        setTimeout(this.closeTip, 1000);
      } else if (result.data.length === 0) {
        this.toUpdateData.isShow = false;
        this.toUpdateData.reports = "";
        this.showAlert("未查询寻到【日报】数据");
        setTimeout(this.closeTip, 1000);
      } else {
        this.$store.dispatch("getReportContentProf", result.data);
        this.toUpdateData.reports = this.reportContentProf;
        if (this.indexOfSingleSelected !== 0) {
          let front = this.toUpdateData.reports.slice(
            0,
            this.indexOfSingleSelected
          );
          let rest = this.toUpdateData.reports.slice(
            this.indexOfSingleSelected
          );
          this.toUpdateData.reports = rest.concat(front);
        }
      }
    },
    async getWeekReport() {
      if (this.member == "") {
        try {
          const result = await year.getGroupThreeWeek({
            date: this.endDate,
            groupId: this.group,
          });
          if (result.code === 0) {
          } else if (result.data.length === 0) {
            this.showAlert("未查询寻到【周报】数据");
            setTimeout(this.closeTip, 1000);
          } else {
            this.$store.commit("stageReportContentWeek", result.data);
          }
        } catch (err) {
          console.log("ERROR" + err);
        }
      } else {
        try {
          const result = await year.getPersonWeekReport({
            date: this.endDate,
            userId: this.member,
          });
          if (result.code === 1) {
            //将code键值对删除，否则遍历的时候会将code也渲染上去，会多出一个没有内容没有头像的itme框；
            // 若将temp.data赋值给this.result，会遍历data，渲染出9个没有内容没有头像的itme框（因为item下有9的属性）
            delete result.code;
            this.$store.commit("stageReportContentWeek", result.data);
          } else {
          }
        } catch (err) {
          console.log("ERROR" + err);
        }
      }
    },
    async getMonthReport() {
      if (this.member == "") {
        try {
          const result = await year.getMonthReportByGroup({
            date: this.endDate,
            groupId: this.group,
          });
          if (result.code === 0) {
          } else if (result.data.length === 0) {
            this.showAlert("未查询寻到【月报】数据");
            setTimeout(this.closeTip, 1000);
          } else {
            this.$store.commit("stageReportContentMonth", result.data);
          }
        } catch (err) {
          console.log("ERROR" + err);
        }
      } else {
        try {
          const result = await year.getPersonMonthReport({
            date: this.endDate,
            userId: this.member,
          });
          if (result.code === 1) {
            delete result.code;
            this.$store.commit("stageReportContentMonth", result.data);
          } else {
          }
        } catch (err) {
          console.log("ERROR" + err);
        }
      }
    },
    async getYearReport() {
      if (this.member == "") {
        try {
          const result = await year.getYearReportByGroup({
            year: this.startDate.slice(0, 4),
            groupId: this.group,
          });
          if (result.code === 0) {
          } else if (result.data.length === 0) {
            this.showAlert("未查询寻到【年报】数据");
            setTimeout(this.closeTip, 1000);
          } else {
            this.$store.commit("stageReportContentYear", result.data);
          }
        } catch (err) {
          console.log("ERROR" + err);
        }
      } else {
        try {
          const result = await year.getPersonYearReport({
            year: this.startDate.slice(0, 4),
            userId: this.member,
          });
          if (result.code === 1) {
            delete result.code;
            this.$store.commit("stageReportContentYear", result.data);
          } else {
          }
        } catch (err) {
          console.log("ERROR" + err);
        }
      }
    },
    async getGraduateReport() {
      if (this.member == "") {
        try {
          const result = await year.getGroupGraduateReport({
            groupId: this.group,
          });
          if (result.code === 0) {
            // do nothing
          } else if (result.data.length === 0) {
            this.showAlert("未查询寻到【毕业总结】数据");
            setTimeout(this.closeTip, 1000);
          } else {
            this.$store.commit("stageReportContentGraduate", result.data);
          }
        } catch (err) {
          console.log("ERROR" + err);
        }
      } else {
        try {
          const result = await year.getSingleGraduateReport({
            userId: this.member,
          });
          if (result.code === 1) {
            delete result.code;
            // 每人只填写一次毕业总结，所以查询单人的毕业总结返回的不是list
            // 强行把它变成list
            let fakeGraduateReportList = [];
            fakeGraduateReportList.push(result.data);
            this.$store.commit(
              "stageReportContentGraduate",
              fakeGraduateReportList
            );
          } else {
            // 将空list放入state，防止显示前一个查询的结果
            this.$store.commit("stageReportContentGraduate", []);
            this.showAlert("该用户未填毕业总结");
            setTimeout(this.closeTip, 1700);
          }
        } catch (err) {
          console.log("ERROR" + err);
        }
      }
    },
    getValueFromDayView(data) {
      this.member = data;
    },
    setToday() {
      let now = new Date();
      let cmonth = now.getMonth() + 1;
      let day = now.getDate();
      let hour = now.getHours();
      if (cmonth < 10) cmonth = "0" + cmonth;
      if (day < 10) day = "0" + day;
      let today = now.getFullYear() + "-" + cmonth + "-" + day;
      this.endDate = today;
    },
    // 搜索点击后显示相应的结果
    showRepoOfThisStudent(data) {
      this.indexOfSingleSelected += data.index;
      this.member = data.member;
    },
    filter(data) {
      this.reportType = data.reportType;
      this.member = data.member;
      this.group = data.group;
      this.startDate = data.startDate;
      this.endDate = data.endDate;
      if(this.member!==''){
        this.getSinglePeriodData()
      }else{
        this.getData();
      }
      // 设置默认群
      group.getSetDefauletGroup({
        groupId:data.group,
        userId:+this.userInfo.userId
      })
      
    },
  },
};
</script>

<style lang="less">
.leftIcon {
  font-size: 20px;
  color: #cccccc;
}

.fullMain {
  background: rgb(237, 237, 237);
  max-height: calc(100% - 40px);
  overflow: hidden;
}

.weui-cells_radio {
  max-height: 250px;
}

.weui-cells_radio .weui-cell__bd p {
  margin: 5px;
}

.weui-cell.vux-tap-active.weui-cell_access {
  padding: 0px 15px;
}

.weui-cells {
  width: 100%;
  margin-top: -20px;
}

.dropdown {
  float: right;
  margin-right: 10px;
  margin-top: 13px;
  background-color: white;
  height: 32px;
}

.search{
  position: fixed;
  top: 46px;
  left: 0;
  width: 100%;
}

.button {
  right: 2rem;
  bottom: 5rem;
  padding: 30px;
  background-color: rgba(26, 188, 156, 0.6);
  border-radius: 100%;
  border-color: rgba(26, 188, 156, 0.6);
  position: fixed;
  z-index: 999;
}

.myHeadIcon {
  display: inline-block;
  width: 50px;
  height: 50px;
  margin-top: 0px;
}

/* // 这里是confirm框的格式 */
.weui-dialog .weui-dialog__bd {
  padding: 0 1.6em 0.8em;
  min-height: 0;
  font-size: 15px;
  line-height: 1.3;
  word-wrap: break-word;
  word-break: break-all;
  color: #999999;
}

.weui-dialog .weui-dialog__btn_default {
  color: #3cc51f;
}

.weui-dialog .weui-dialog__btn_primary {
  color: red;
}

.list_item {
  margin: 0 5px;
  padding: 10px 5px;
  display: inline-flex;
}

// 各种汇报的公共显示样式

.myHeadIcon {
  display: inline-block;
  width: 50px;
  height: 50px;
  margin-top: 0px;
}
.name {
  font-family: "华文楷体";
  color: rgb(136, 136, 136);
}
.place {
  font-family: "微软雅黑";
  font-size: 14px;
  color: gray;
}
.triangle {
  margin-left: -10px;
  margin-right: -5px;
  margin-top: 35px;
  display: inline-block;
  height: 0;
  width: 0;
  border: 10px solid transparent;
  border-right: 10px solid white;
}
.content {
  // line-height: 20px;
  width: 100%;
  margin-right: 10px;
}
.groupDiv {
  padding-top: 10px;
  margin-top: 80px;
  max-height: 1000px;
  overflow: scroll;
  width: auto;
  background-color: rgb(237, 237, 237);
}
.tag {
  font-family: "微软雅黑 Light";
  display: inline-block;
  text-align: left;
  // font-size: 17px;
  font-weight: bold;
  color: rgb(101, 101, 101);
}
.content-detail {
  background-color: white;
  border-radius: 5px;
}
.content-detail p {
  margin-left: 1px;
  margin-bottom: 5px;
  margin-top: 10px;
  letter-spacing: 0.5px;
  color: grey;
  font-size: small;
  font-family: "微软雅黑";
  letter-spacing: 0.5px;
  margin: 5px;
}

.content-detail p span {
  font-size: small;
  color: rgb(191, 191, 191);
}

* {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
input,
textarea {
  -webkit-user-select: auto;
}
</style>
